package cn.seaboot.commons.http.call;

import cn.seaboot.commons.core.Asserts;
import cn.seaboot.commons.http.HttpStatusException;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 后台数据响应为一份文件，将文件复制到一个输出流中
 *
 * 当前写法固然是能执行，但不是什么好的写法，应当在数据响应的时候，在开启输出流，减少文件的占用时间。
 *
 * @author Mr.css
 * @version 2025-02-14 9:59
 */
public class OutputHandler implements HttpClientResponseHandler<Object> {

    private final OutputStream outputStream;

    public OutputHandler(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    @Override
    public Object handleResponse(ClassicHttpResponse response) throws IOException {
        int code = response.getCode();
        if (code != HttpStatus.SC_OK) {
            throw new HttpStatusException("Error status :" + code);
        }
        HttpEntity entity = response.getEntity();
        Asserts.notNull(entity, "http response entity is null!");
        entity.writeTo(outputStream);
        return null;
    }
}
